package cn.aitrox.ry.service.anno.dao.impl;

import cn.aitrox.ry.common.bean.Order;
import cn.aitrox.ry.common.dao.MapperSqlCallback;
import cn.aitrox.ry.common.dao.impl.BaseDaoImpl;
import cn.aitrox.ry.service.anno.dao.UserTaskDao;
import cn.aitrox.ry.service.anno.entity.TaskEntity;
import cn.aitrox.ry.service.anno.entity.UserTaskEntity;
import cn.aitrox.ry.service.anno.enumtype.task.TaskStatusEnum;
import cn.aitrox.ry.service.anno.mapper.UserTaskMapper;
import cn.aitrox.ry.service.anno.po.user.task.UserTaskFindCondPo;
import cn.aitrox.ry.util.ArrayUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

@Repository
public class UserTaskDaoImpl extends BaseDaoImpl<UserTaskEntity> implements UserTaskDao {

    @Autowired
    private UserTaskMapper mapper;

    @Override
    public List<UserTaskEntity> findByUserIdStatus(Integer userId, Integer... status) {
        return mapper.findByUserIdStatusOrderBy(userId, status, Order.desc(UserTaskEntity.COL_JOIN_TIME));
    }

    @Override
    public PageInfo<TaskEntity> searchTaskByCustom(Integer page, Integer pageSize, UserTaskFindCondPo cond) {
        return searchResultByCustom(page, pageSize, Order.desc("task_id"), new MapperSqlCallback<TaskEntity>() {
            @Override
            public List<TaskEntity> invoke() {
                return mapper.findTaskByCond(cond);
            }
        });
    }

    @Override
    public void batchSave(List<UserTaskEntity> list) {
        if (ArrayUtil.isEmpty(list)) {
            return;
        }
        super.batchInsert(list, 2000, new MapperSqlCallback<UserTaskEntity>() {
            @Override
            public void batchInsert(List<UserTaskEntity> objList) {
                mapper.batchInsert(objList);
            }
        });
    }

    @Override
    public UserTaskEntity findByUserIdTaskId(Integer userId, Integer taskId) {
        UserTaskEntity cond = new UserTaskEntity(null, userId, taskId, null, null, null, null);
        return super.findOne(cond);
    }

    @Override
    public List<UserTaskEntity> findByUserIdTaskIds(Integer userId, List<Integer> taskIds) {
        return mapper.findByUserIdTaskIds(userId, taskIds);
    }

    @Override
    public void terminate(Integer taskId) {
        if (null == taskId) {
            return;
        }
        UserTaskEntity cond = new UserTaskEntity();
        cond.setTaskId(taskId);
        List<UserTaskEntity> userTaskList = super.findByCondition(cond, null);
        if (ArrayUtil.isEmpty(userTaskList)) {
            return;
        }
        UserTaskEntity update = new UserTaskEntity();
        update.setStatus(TaskStatusEnum.TERMINATE.getStatus());
        super.updateByIdsSelective(update, userTaskList.stream().map(UserTaskEntity::getId).collect(Collectors.toList()).toArray());
    }
}
